package com.tscnd.core.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import com.tscnd.core.Constants;

/**
 * Date Utility Class This is used to convert Strings to Dates and Timestamps
 * 
 * <p>
 * <a href="DateUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a> Modified by
 *         <a href="mailto:dan@getrolling.com">Dan Kibler </a> to correct time
 *         pattern. Minutes should be mm not MM (MM is month).
 * @version $Revision: 1.3 $ $Date: 2014/05/04 09:22:01 $
 */
public class DateUtils {
	// ~ Static fields/initializers
	// =============================================

	private static Log log = LogFactory.getLog(DateUtils.class);
	private static String defaultDatePattern = "yyyy-MM-dd";
	private static String yearPattern = "yyyy年";
	private static String monthPattern = "yyyy年MM月";
	private static String dayTimePattern = "yyyy-MM-dd HH:mm:ss";
	// ~ Methods
	// ================================================================


	/**
	 * Return default datePattern (yyyy年MM月dd日)
	 * 
	 * @return a string representing the date pattern on the UI
	 */
	public static String getDefaultDatePattern() {
		Locale locale = LocaleContextHolder.getLocale();
		try {
			defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY,
					locale).getString("date.format");
		} catch (MissingResourceException mse) {
			defaultDatePattern = "yyyy-MM-dd";
		}

		return defaultDatePattern;
	}

	public static String getDefaultDateTimePattern() {
		Locale locale = LocaleContextHolder.getLocale();
		try {
			dayTimePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY,
					locale).getString("datetime.format");
		} catch (MissingResourceException mse) {
			dayTimePattern = "yyyy-MM-dd HH:mm:ss";
		}
		return dayTimePattern;
	}


	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see java.text.SimpleDateFormat
	 * @throws ParseException
	 */
	public static final Date convertStringToDate(String aMask, String strDate)
			throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat(aMask);

		if (log.isDebugEnabled()) {
			log.debug("converting '" + strDate + "' to date with mask '"
					+ aMask + "'");
		}

		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			// log.error("ParseException: " + pe);
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	
	/**
	 * This method generates a string representation of a date's date/time in
	 * the format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param aDate
	 *            a date object
	 * @return a formatted string representation of the date
	 * 
	 * @see java.text.SimpleDateFormat
	 */
	public static final String convertDateToString(String aMask, Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {

			// log.error("aDate is null!");
			return "";
		} else {
			df = new SimpleDateFormat(aMask);
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}
	
	/**
	 * This method generates a string representation of a date based on the
	 * System Property 'dateFormat' in the format you specify on input
	 * 
	 * @param aDate
	 *            A date to convert
	 * @return a string representation of the date
	 */
	public static final String convertDateToString(Date aDate) {
		return convertDateToString(getDefaultDatePattern(), aDate);
	}
	
	/**
	 * This method converts a String to a date using the datePattern
	 * 
	 * @param strDate
	 *            the date to convert (in format MM/dd/yyyy)
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static Date convertStringToDate(String strDate)
			throws ParseException {
		Date aDate = null;
		aDate = convertStringToDate(getDefaultDatePattern(), strDate);
		return aDate;
	}

	/**
	 * This method returns the current date in the format: MM/dd/yyyy
	 * 
	 * @return the current date
	 * @throws ParseException
	 */
	public static Calendar getToday() throws ParseException {
		Date today = new Date();
		// This seems like quite a hack (date -> string -> date),
		// but it works ;-)
		String todayAsString = convertDateToString(getDefaultDatePattern(), today);
		Calendar cal = new GregorianCalendar();
		cal.setTime(convertStringToDate(todayAsString));
		return cal;
	}
	
	/**
	 * This method returns the current date in the format: MM/dd/yyyy
	 * 
	 * @return the current date
	 * @throws ParseException
	 */
	public static Date getTodayDate() throws ParseException {
		return getToday().getTime();
		
	}

	/**
	 * 
	 * yyyy年MM月dd日 HH时mm分";
	 * 
	 * @param strDate
	 *            the date to convert yyyy年MM月dd日 HH时mm分";
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static Date convertStringToDatetime(String strDate)
			throws ParseException {
		return convertStringToDate(getDefaultDateTimePattern(),strDate);
	}

	/**
	 * 
	 * yyyy年MM月dd日 HH时mm分";
	 * 
	 * @param strDate
	 *            the date to convert yyyy年MM月dd日 HH时mm分";
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static String convertDatetimeToString(Date dateTime)
			throws ParseException {
			return convertDateToString(getDefaultDateTimePattern(),dateTime);
	}
	
	
	/**
	 * 转换成yyyy年MM月 形,字符串
	 */
	public static String convertDateToMonthString(Date sDate) {
		return convertDateToString(monthPattern, sDate);

	}
	

	/**
	 * 转换成yyyy年 形,字符串
	 */
	public static String convertDateToYearString(Date sDate) {
		return convertDateToString(yearPattern, sDate);

	}
	

	/**
	 * 转换成yyyy年 形,字符串
	 */
	public static String convertDateToYearString(String s) {
		String sDate = null;
		if (s != null && s.length() >= 5) {
			sDate = s.substring(0, 5);
		}
		return sDate;

	}

	/**
	 * 转换成yyyy年MM月 形,字符串
	 */
	public static String convertDateToMonthString(String s) {
		String sDate = null;
		if (s != null && s.length() >= 8) {
			sDate = s.substring(0, 8);
		}
		return sDate;

	}

	/**
	 * 获得当前系统时间
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static Date getCurrentDate() {
		return new Date(System.currentTimeMillis());

	}

	/**
	 * 获得当前年份
	 * 
	 * @return
	 * 
	 *         631wj int
	 */
	public static int getCurrentYear() {
		Date date = getCurrentDate();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal.get(Calendar.YEAR);
	}
	
	/**
	 * 获得当前月份
	 * 
	 * @return
	 * 
	 *         631wj int
	 */
	public static int getCurrentMonth() {
		Date date = getCurrentDate();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal.get(Calendar.MONTH);
	}

	/**
	 * 时间的年份
	 * 
	 * @return
	 * 
	 *         631wj int
	 */
	public static int getYearofDate(Date date) {
		if (date == null) {
			return 0;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal.get(Calendar.YEAR);
	}

	/**
	 * 获得当前系统时间
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String getCurrentStrDate() {
		return convertDateToString(new Date(System.currentTimeMillis()));

	}

	/**
	 * 获得当前系统时间
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String getCurrentMonthStrDate() {
		return convertDateToMonthString(new Date(System.currentTimeMillis()));

	}

	/**
	 * 将 yyyy、yyyyMM、yyyyMMdd 格式的字符串转换为日期
	 * 
	 * @param str
	 * @return
	 */
	public static Date toDate(String str) {
		Date date = null;
		if (!StringUtils.isEmpty(str)) {
			try {
				if (str.length() == 12) {
					date = DateUtils.convertStringToDate("yyyyMMddHHmm",
							str.substring(0, 12));
				} else if (str.length() == 8) {
					date = DateUtils.convertStringToDate("yyyyMMdd",
							str.substring(0, 8));
				} else if (str.length() == 6) {
					date = DateUtils.convertStringToDate("yyyyMM",
							str.substring(0, 6));
				} else if (str.length() == 4) {
					date = DateUtils.convertStringToDate("yyyy",
							str.substring(0, 4));
				}
			} catch (ParseException e) {
				return date;
			}
		}
		return date;
	}

	/**
	 * 将 yyyy.、yyyy.MM、yyyy.MM.dd 格式的字符串转换为日期
	 * 
	 * @param str
	 * @return
	 */
	public static Date toDotDate(String str) {
		Date date = null;
		if (!StringUtils.isEmpty(str)) {
			try {
				if (str.length() >= 10) {
					date = DateUtils.convertStringToDate("yyyy.MM.dd",
							str.substring(0, 10));
				} else if (str.length() == 7) {
					date = DateUtils.convertStringToDate("yyyy.MM",
							str.substring(0, 7));
				} else if (str.length() == 4) {
					date = DateUtils.convertStringToDate("yyyy",
							str.substring(0, 4));
				}
			} catch (ParseException e) {
				return date;
			}
		}
		return date;
	}

	/**
	 * 将 yyyy、yyyy-MM、yyyy-MM-dd 格式的字符串转换为日期
	 * 
	 * @param str
	 * @return
	 */
	public static Date convertStringToStrigulaDate(String str) {
		Date date = null;
		if (!StringUtils.isEmpty(str)) {
			try {
				if (str.length() >= 10) {
					date = DateUtils.convertStringToDate("yyyy-MM-dd",
							str.substring(0, 10));
				} else if (str.length() == 7) {
					date = DateUtils.convertStringToDate("yyyy-MM",
							str.substring(0, 7));
				} else if (str.length() == 4) {
					date = DateUtils.convertStringToDate("yyyy",
							str.substring(0, 4));
				}
			} catch (ParseException e) {
				return date;
			}
		}
		return date;
	}

	/**
	 * 将 yyyy年、yyyy年MM月、yyyy年MM月dd日 格式的字符串转换为日期
	 * 
	 * @param str
	 * @return
	 */
	public static Date convertStringToMoreDate(String str) {
		Date date = null;
		if (!StringUtils.isEmpty(str)) {
			try {
				if (str.length() > 11) {
					date = DateUtils.convertStringToDatetime(str);
				}
				if (str.length() == 11) {
					date = DateUtils.convertStringToDate(getDefaultDatePattern(), str);
				} else if (str.length() == 8) {
					date = DateUtils.convertStringToDate(monthPattern, str);
				} else if (str.length() == 5) {
					date = DateUtils.convertStringToDate(yearPattern, str);
				}
			} catch (ParseException e) {
				return date;
			}
		}
		return date;
	}



	/**
	 * 转换成yyyy年1月1日 代表这一年的开始 是年度数据
	 * 
	 * @throws ParseException
	 */
	public static Date getCurrentYearDate() {
		try {
			return convertStringToDate(yearPattern,
					convertDateToYearString(getCurrentDate()));
		} catch (ParseException e) {
			return null;
		}

	}

	/**
	 * 获得日期的日
	 */
	public static int getDayNum(Date date) {
		if (date == null) {
			return 0;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DATE);
	}

	/**
	 * 将日期转化为yyyy-MM-dd HH:mm:ss这种形式
	 * 
	 * @param date
	 * @return String
	 */
	public static String convertDateToDayString(Date date) {

		return convertDateToString(dayTimePattern, date);
	}
	
	
	/**
	 * 将日期转化为yyyy-MM-dd HH:mm这种形式
	 * 
	 * @param date
	 * @return String
	 */
	public static String convertDateTodString(Date date) {

		return convertDateToString(dayTimePattern, date);
	}
	
	
	/**
	 * date:2010.03.01 author:jw 日期加天数返回日期
	 */
	public static Date addDate(Date d, long day) throws ParseException {
		long time = d.getTime();
		day = day * 24 * 60 * 60 * 1000;
		time += day;
		return new Date(time);

	}

	// 1026 jw
	/**
	 * 获得日期的月份
	 */
	public static int getMonthNum(Date date) {
		if (date == null) {
			return 0;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MONTH) + 1;
	}

	/**
	 * 获得日期的年份
	 * 
	 * @param date
	 * @return
	 */
	public static int getYearNum(Date date) {
		if (date == null) {
			return 1900;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.YEAR);
	}

	/**
	 * 获得月份加减后的字符串
	 * 
	 * @param date
	 * @param num
	 *            (包括+,-)
	 * @param pattern
	 * @return
	 */
	public static String getMonthSubString(Date date, int num) {
		if (date == null) {
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, num);
		SimpleDateFormat df = new SimpleDateFormat(monthPattern);
		return df.format(cal.getTime());
	}

	/**
	 * 获得日期加减
	 * 
	 * @param date
	 * @param num
	 *            (包括+,-)
	 * @param pattern
	 * @return
	 */
	public static Date getDayUpOrDown(Date date, int num) {
		if (date == null) {
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, num);
		return cal.getTime();
	}


	/**
	 * 获得同年的两个月份之间的月份数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getMonthSubNum(Date date1, Date date2) {
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date1);
		Calendar c2 = Calendar.getInstance();
		c2.setTime(date2);
		return (c2.get(1) - c1.get(1)) * 12 + (c2.get(2) - c1.get(2));
	}
	/**
	 * 获得获得时间的天数差值
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	 public static int betweenDays(Calendar beginDate, Calendar endDate) {
		      return (int)((beginDate.getTimeInMillis() - endDate.getTimeInMillis())/(1000*60*60*24));
		    
	 }
	/**
	 * 获得获得时间的天数差值
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	 public static int betweenDays(Date beginDate, Date endDate) {
			Calendar c1 = Calendar.getInstance();
			c1.setTime(beginDate);
			Calendar c2 = Calendar.getInstance();
			c2.setTime(endDate);  
			return betweenDays(c1,c2);
	 }

	public static void main(String[] args) throws ParseException {
		Date de=new Date(System.currentTimeMillis());
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		System.out.println(formatter.format(de));
		System.out.println(convertDateToString(new Date()));
		String sms="LHS-1335-12";
		System.out.println(sms.replaceAll("[a-zA-Z-]{4}", ""));
		System.out.println(getYearNum(new Date()));
	}

}
